//
//  HZNetWorkAgent.m
//  httpDemo
//
//  Created by admin on 15/11/30.
//  Copyright © 2015年 admin. All rights reserved.
//

#import "HZNetWorkAgent.h"
//#import "UIUtils.h"
#import "AppDelegate.h"
#import <UIKit/UIKit.h>

@implementation HZNetWorkAgent{
    AFHTTPRequestOperationManager * manager;
    NSMutableDictionary * requestRecord;
    
    AppDelegate * dele;//获取根
    UIImageView * failureImageV;
}
//编写单例模式
+(HZNetWorkAgent *)shareInstance{
    static id shareInstance = nil;
    static dispatch_once_t once_Token;
    dispatch_once(&once_Token, ^{
        shareInstance =[[self alloc] init];
    });
    return shareInstance;
}
-(id)init{
    self = [super init];
    if(self){
        manager = [AFHTTPRequestOperationManager manager];
        requestRecord = [NSMutableDictionary dictionary];
        manager.operationQueue.maxConcurrentOperationCount = 4;
        
        _HUD = [[MBProgressHUD alloc] initWithFrame:CGRectZero];
        dele = [UIApplication sharedApplication].delegate;
        [dele.window.rootViewController.view addSubview:_HUD];
        
//        failureImageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 20, dele.window.rootViewController.view.frame.size.width,  dele.window.rootViewController.view.frame.size.height-20)];
//        failureImageV.image = [UIImage imageNamed:@"404v4.png"];
//        failureImageV.hidden = YES;
//        failureImageV.userInteractionEnabled = YES;
//        //[dele.window addSubview:failureImageV];
//        UITapGestureRecognizer * tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(failureImageClick)];
//        [failureImageV addGestureRecognizer:tapGes];
       // [failureImageV setImageWithURL:[NSURL URLWithString:@""] placeholderImage:[UIImage imageNamed:@""]];
        
    }
    return self;
}

-(void)addRequest:(HZBaseRequest *)request{
    HZRequestMethod method = request.requestMethod;
    NSString * url = [[NSString stringWithFormat:@"%@%@",request.baseUrl,request.requestUrl] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSDictionary * param = request.requestParam;
    
    if(request.requestSerializerType == HZRequestSerializerTypeHttp){
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        
    }else if (request.requestSerializerType == HZRequestSerializerTypeJson){
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/xml"];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
       // manager.requestSerializer = [AFJSONRequestSerializer serializer];
    }
    
    _HUD.mode=MBProgressHUDAnimationFade;
    _HUD.labelText = @"Loading...";
    _HUD.labelColor = [UIColor lightGrayColor];
    [_HUD show:YES];
    
    if(method == HZRequestMethodGet){
  
        request.requestOperation = [manager GET:url parameters:param success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
            
            [self handleRequestResult:operation];
        } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
            
            [self handleRequestResult:operation];
        }];
    }else if (method == HZRequestMethodPost){
        request.requestOperation = [manager POST:url parameters:param success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
            
            [self handleRequestResult:operation];
            
        } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
            
            [self handleRequestResult:operation];
        }];
    }
    
    [self addOperation:request];
}
- (void)handleRequestResult:(AFHTTPRequestOperation *)operation {
    [_HUD hide:YES];
    if(failureImageV.hidden==NO){
        [failureImageV removeFromSuperview];
    }
    NSString * key = [self requestHashKey:operation];
    HZBaseRequest *request = requestRecord[key];
    if (request) {
        BOOL succeed = [self checkResult:request];
        if (succeed) {
            if (request.successCompetionBlock) {
                request.successCompetionBlock(request,YES);
            }
        }else {
            if (request.successCompetionBlock) {
                 request.successCompetionBlock(request,NO);
            }
        }
    }
    [self removeOperation:operation];
    [request clearCompletionBlock];
}
- (BOOL)checkResult:(HZBaseRequest *)request{

    BOOL result = [request statusCodeValidator];
    return result;
}

- (void)addOperation:(HZBaseRequest *)request {
    if (request.requestOperation != nil) {
        NSString * key = [self requestHashKey:request.requestOperation];
        requestRecord[key] = request;
    }
}
- (NSString *)requestHashKey:(AFHTTPRequestOperation *)operation
{
    NSString *key = [NSString stringWithFormat:@"%lu", (unsigned long)[operation hash]];
    return key;
}
- (void)removeOperation:(AFHTTPRequestOperation *)operation {
    NSString * key = [self requestHashKey:operation];
    [requestRecord removeObjectForKey:key];
}

-(void)requestUrl:(NSString *)url param:(NSDictionary *)requestAgument baseUrl:(NSString *)baseUrl withRequestMethod:(HZRequestMethod)requestMethod withCompletionWithSuccess:(void (^)(HZBaseRequest * ,BOOL isSuccess))success withTag:(NSInteger)tag{

    HZBaseRequest * base = [[HZBaseRequest alloc] init];//[HZBaseRequest shareRequestInstance];
    base.baseUrl = baseUrl;
    base.requestUrl = url;
    base.tag = tag;
    base.requestParam = requestAgument;
    base.requestMethod = requestMethod;
    base.successCompetionBlock = success;
  //base.failureCompetionBlock = failure;
    [self addRequest:base];
    //判断网络
//    BOOL isExistNetWork = [UIUtils isConnectionAvailable];
//    if(!isExistNetWork){
////        failureImageV.hidden = NO;
////         [_HUD.superview bringSubviewToFront:failureImageV];
//        
//        [UIUtils addMiddleRemindInfomationWithText:@"无网络连接" FontSize:14 ToView:_HUD.superview];
//        return;
//    }else{
//      //  [failureImageV removeFromSuperview];
//        
//    }
    
    
}
- (void)cancelRequest:(NSInteger)tag {
    NSDictionary *copyRecord = [requestRecord copy];
    for (NSString *key in copyRecord) {
        HZBaseRequest *request = copyRecord[key];
        if (request.tag == tag) {
            [request.requestOperation cancel];
            [self removeOperation:request.requestOperation];
            [request clearCompletionBlock];
        }
    }
}
- (void)cancelAllRequests {
    NSDictionary *copyRecord = [requestRecord copy];
    for (NSString *key in copyRecord) {
        HZBaseRequest *request = copyRecord[key];
        [request stop];
    }
}


-(void)postUpLoadImageWithUrl:(NSString *)url image:(UIImage *)image completion:(void (^)(BOOL isSuc,NSString * responseStr))success{
    _HUD.mode=MBProgressHUDAnimationFade;
    _HUD.labelText = @"正在上传";
    _HUD.labelColor = [UIColor lightGrayColor];
    [_HUD show:YES];
    
    self.imageUpLoad = success;
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
     //   NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"头像1.png" withExtension:nil];
        NSData *data = UIImagePNGRepresentation(image);
        // 要上传保存在服务器中的名称
        // 使用时间来作为文件名 2014-04-30 14:20:57.png
        // 让不同的用户信息,保存在不同目录中
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置日期格式
        formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSString *fileName = [formatter stringFromDate:[NSDate date]];
        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [_HUD hide:YES];
        self.imageUpLoad(YES,operation.responseString);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [_HUD hide:YES];
        self.imageUpLoad(NO,operation.responseString);
    }];
}

-(void)postUpLoadImagesWithUrl:(NSString *)url images:(NSArray *)imageArray completion:(void (^)(BOOL isSuc,NSString * responseStr))success
{
    
    _HUD.mode=MBProgressHUDAnimationFade;
    _HUD.labelText = @"正在上传";
    _HUD.labelColor = [UIColor lightGrayColor];
    [_HUD show:YES];
    
    self.imageUpLoad = success;
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

//    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//    // 设置日期格式
//    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
//    
//    NSDate *date = [NSDate date];
//    NSTimeInterval time = [date timeIntervalSince1970];
//
    NSInteger Image_Name = arc4random()%99;
    // 显示进度
    [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
     {
         // 上传 多张图片
         for(NSInteger i = 0; i <imageArray.count; i++)
         {
             NSData * imageData = [imageArray objectAtIndex: i];
             // 上传的参数名
           //  time=time+i;
            // NSString *fileName = [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:time]];
             NSString * fileName = [NSString stringWithFormat:@"%ld", Image_Name+i+1];
             [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpeg"];
         }
     }success:^(AFHTTPRequestOperation *operation, id responseObject){
         [_HUD hide:YES];
         self.imageUpLoad(YES,operation.responseString);
     }failure:^(AFHTTPRequestOperation *operation, NSError *error){
         [_HUD hide:YES];
         self.imageUpLoad(NO,operation.responseString);
     }];
    
    
    
}
//-(void)failureImageClick{
//    
//    HZBaseRequest * request = [HZBaseRequest shareRequestInstance];
//    [self addRequest:request];
//}
@end
